<?php
/**
 * $Id: mysql.php 19 2009-06-08 08:45:14Z eyou80 $
 */

/** 载入PDO适配器抽象类 **/
require_once 'Tinyask/db/adapter/pdo.php';

/**
 * 数据库Pdo_Mysql适配器
 *
 * @package Db
 */
class Tinyask_Db_Adapter_Pdo_Mysql extends Tinyask_Db_Adapter_Pdo
{
	/**
	 * 判断适配器是否可用
	 *
	 * @return boolean
	 */
	public static function isAvailable()
	{
		return parent::isAvailable() && in_array('mysql', PDO::getAvailableDrivers());
	}

	/**
	 * 数据库连接
	 *
	 * @param Tinyask_Config $config
	 * @return PDO
	 */
	public function init(Tinyask_Config $config)
	{
		$pdo = new PDO("mysql:dbname={$config->database};host={$config->host};port={$config->port}", $config->user, $config->password);
		$pdo->exec("SET NAMES '{$config->charset}'");
		return $pdo;
	}

	/**
	 * 转义值
	 *
	 * @param string $string
	 * @return string
	 */
	public function quoteValue($string)
	{
		return '\'' . str_replace(array('\'', '\\'), array('\'\'', '\\\\'), $string) . '\'';
	}

	/**
	 * 转义字段名称
	 *
	 * @param string $string
	 * @return string
	 */
	public function quoteField($string)
	{
		return '`' . $string . '`';
	}

	/**
	 * 合成sql查询语句
	 *
	 * @param array $sql
	 * @return string
	 */
	public function mergeSelect(array $sql)
	{
		if(!empty($sql['join'])) {
			foreach($sql['join'] as $val) {
				list($table, $condition, $op) = $val;
				$sql['table'] .= " $op JOIN $table ON $condition";
			}
		}

		$sql['limit'] = (strlen($sql['limit']) == 0)  ? null : ' LIMIT ' . $sql['limit'];
		$sql['offset'] = (strlen($sql['offset']) == 0) ? null : ' OFFSET ' . $sql['offset'];

		return 'SELECT ' . $sql['fields'] . ' FROM ' . $sql['table'] .
		$sql['where'] . $sql['group'] . $sql['order'] . $sql['limit'] . $sql ['offset'];
	}
}
